<?php
namespace App\Http\Controllers\Api\Ly;
use App\Common\Responses;
use App\Utils\Logic\Ly\Logingic;
use App\Utils\Service\Ly\JwtServer;
use App\Http\Controllers\Controller;
use App\Utils\Service\Ly\WxLogin;
use Illuminate\Http\Request;
use \App\Models\Ly\wxLogin as wxLoginModel;
class LoginController extends Controller
{
    /**
     * 手机号登录
     * @param Request $request
     * @return false|string
     * @name ly
     */
    public function login(Request $request)
    {
        try {
            $phone=$request->post('phone');
            $code=$request->post('code');
            Logingic::login($phone,$code);
            return Responses::success([],200,'登录成功');
        }catch (\Exception $e)
        {
            return Responses::error([],550,$e->getMessage());
        }
    }

    /**
     * 发送短信验证码
     * @param Request $request
     * @return false|string
     * @throws \Exception
     * @name ly
     */
    public function send(Request $request)
    {
        try {
            $phone=$request->post('phone');
            $code=Logingic::send($phone);
            return Responses::success($code,200,'短信验证码发送成功');
        }catch (\Exception $e)
        {
            return Responses::error([],550,$e->getMessage());
        }
    }

    /**
     * 授权登录
     * @param Request $request
     * @return false|string
     * @name ly
     */
    public function User(Request $request)
    {
        try {
            $params = $request->post();
            $userInfo = WxLogin::getOpenidByCode($params['code']);
            $data = [
                'openid' => $userInfo['openid'],
                'session_key' => $userInfo['session_key'],
                'nickName' => $params['nickName'],
                'avatarUrl' => $params['avatarUrl'],
            ];
            $user=wxLoginModel::getOne($data);
            if(empty($user))
            {
                wxLoginModel::add($data);
            }else {
                wxLoginModel::edit($data);
            }
            $token=JwtServer::encode($user['id']);
            return Responses::success($token,200,'登录成功');
        }catch (\Exception $e) {
            return Responses::error([],550,$e->getMessage());
        }

    }
}
